<?php
namespace app\api\controller;
use app\common\controller\IndexBase;
use app\api\model\Wechat as Weixin;
use app\common\model\User;
use think\facade\Request;
use think\facade\Db;
use think\facade\Cache;
use think\facade\Session;
use app\common\model\Shop;
use app\common\model\WechatUser;

class Wechat extends IndexBase
{
    protected function _initialize()
    {
        parent::_initialize();
    }
    //小程序授权登录
    public function login()
    {
        $code = input('code');
        $app = Weixin::wxapp();
        $userinfo = $app->auth->session($code);
        //添加数据库
        $json_obj = json_decode(input('user_info'),true);
        db('user')->where(['openid'=>$userinfo['openid']])->update([
            'openid'   => $userinfo['openid'],
            'avatar'   => $json_obj['avatar'],
            'nickname' => $json_obj['nickname'],
            'country'  => $json_obj['country'],
            'province' => $json_obj['province'],
            'city'     => $json_obj['city'],
            'gender'   => $json_obj['gender']
        ]);
        return json([
            'code' => 'ok',
            'msg' => '登陆成功',
            'data' => [
                'userinfo' => $json_obj,
                'u' => $userinfo,
            ],
        ]);
    }
    //小程序授权手机号码登录
    public function phone_login()
    {
        //获取OPENID等
        $code = input('code');
        $encryptedData = input('encryptedData');
        $iv = input('iv');
        $app = Weixin::wxapp();
        $session = $app->auth->session($code);
        $result = $app->encryptor->decryptData($session['session_key'], $iv, $encryptedData);
        //检查账户情况
        $user = User::with('shop')->where(['mobile'=>$result['phoneNumber']])->order('id desc')->find();
        //检查是否禁用
        if($user['status'] != 1){
            $this->result($user, '-2', '账号已禁用','json');
        }
        $user['shop_name'] == '' && $this->result($user, '-2', '禁止登陆','json');
        //检查是否过期
        if($user['exp_time'] < date('Y-m-d',time())){
            $this->result($user, '-2', '您的账户已过期','json');
        }
        // 保存session状态
        $auth = [
            'user_id' => $user['id'],
            'shop_id' => $user['shop_id'],
            'exp_time' => $user['exp_time'],
            'mobile' => $user['mobile'],
            'openid' => $session['openid'],
        ];
        Session::set('user_auth', $auth);
        Session::set('user_auth_sign', data_auth_sign($auth));
        $user['sessionid'] = Session::getId();
        // 更新信息
        User::where(['id' => $user['id']])->update([
            'last_login_ip'   => $this->request->ip(),
            'login_count'     => $user['login_count'] + 1,
        ]);
        $this->result($user, '0', '登陆成功','json');
    }
    //获取验证码
    public function get_code($mobile)
    {
        //检查手机号码格式
        try{
            $this->validate(['mobile'=>$mobile], 'mobile');
        }catch (\Exception $e){
            $this->result('', '-3',$e->getMessage(), 'json');
        }
        //检查当天验证次数
        $code = UserCode::where(['mobile'=> $mobile])->whereDay('create_time')->order('id desc')->count();
        if($code > '5'){
            $this->result('', '-3', '验证次数超额,请明天再试!', 'json');
        }
        //创建验证码
        $code = rand_number(6);
        UserCode::create(['shop_id'=> ShopId(),'mobile'=>$mobile,'code'=>$code,'exp_time'=>time()+600]);
        \app\common\model\Sms::sendCode($mobile,$code);
        $this->result('', '0', '发送成功', 'json');
    }
    //注册
    public function register()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $code = UserCode::where(['mobile'=>$param['mobile'],'code'=>$param['code']])->order('id desc')->find();
            //验证码是否正确
            if(!$code){
                $this->result('', '-3', '验证码错误!', 'json');
            }
            //验证码是否过期
            if($code['exp_time'] < time()){
                $this->result('', '-3', '验证码过期!', 'json');
            }
            //新增商户
            $authgroup['shop_id'] = Shop::insertGetId([
                'name'         =>  $param['name'],
                'province'     =>  $param['province'],
                'city'         =>  $param['city'],
                'area'         =>  $param['area'],
                'address'      =>  $param['address'],
                'mobile'       =>  $param['mobile'],
                'exp_time'     =>  strtotime("+1month",time()),  
                'create_time'  =>  time(),
                'update_time'  =>  time()
            ]);
            $authgroup['name'] = "管理员";
            $authgroup['status'] = "1";
            $rules = \app\common\model\UserAuthRule::where('status',1)->order('id desc')->column('id');
            $authgroup['rules'] = implode(",", $rules);
            //$authgroup['rules'] = "26,1,2,3,4,5,27,51,6,7,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,48,49,50";
            $authgroup['create_time'] = $authgroup['update_time'] = time();
            $groupid = \app\common\model\UserAuthGroup::insertGetId($authgroup);
            //添加超级管理员
            $adduser['shop_id'] = $authgroup['shop_id'];
            $adduser['name'] = $param['name'];
            $adduser['mobile'] = $param['mobile'];
            $adduser['password'] = '123456';
            $adduser['status'] = "1";
            $adduser['group_id'] = $groupid;
            User::create($adduser);
            $this->result('', '0', '注册成功','json');
        }
    }
    //微信支付回调
    public function notify_url()
    {
        $app = Weixin::payminiapp();
        $response = $app->handlePaidNotify(function ($message, $fail) {
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $order = ShopOrder::where(['orderid'=>$message['out_trade_no']])->find();

            if (!$order || $order['status']>='1') { // 如果订单不存在 或者 订单已经支付过了
                return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            ///////////// <- 建议在这里调用微信的【订单查询】接口查一下该笔订单的情况，确认是已经支付 /////////////
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    ShopOrder::where(['orderid'=>$message['out_trade_no']])->update([
                        'status'      => '1',
                        'update_time' => time()
                    ]);
                // 用户支付失败
                } elseif ($message['result_code'] === 'FAIL') {
                    ShopOrder::where(['orderid'=>$message['out_trade_no']])->update([
                        'status'      => '2',
                        'update_time' => time()
                    ]);
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            return true; // 返回处理完成
        });

        $response->send(); // Laravel 里请使用：return $response;
    }
    //体验登陆
    public function tiyan()
    {
        //检查账户情况
        $user = User::with('shop')->where(['mobile'=>'13055556455'])->order('id desc')->find();
        //检查是否禁用
        if($user['status'] != 1){
            $this->result($user, '-2', '账号已禁用','json');
        }
        $user['shop_name'] == '' && $this->result($user, '-2', '禁止登陆','json');
        //检查是否过期
        if($user['exp_time'] < date('Y-m-d',time())){
            $this->result($user, '-2', '您的账户已过期','json');
        }
        // 保存session状态
        $auth = [
            'user_id' => $user['id'],
            'shop_id' => $user['shop_id'],
            'exp_time' => $user['exp_time'],
            'mobile' => $user['mobile'],
            //'openid' => $session['openid'],
        ];
        Session::set('user_auth', $auth);
        Session::set('user_auth_sign', data_auth_sign($auth));
        $user['sessionid'] = Session::getId();
        // 更新信息
        User::where(['id' => $user['id']])->update([
            'last_login_ip'   => $this->request->ip(),
            'login_count'     => $user['login_count'] + 1,
        ]);
        $this->result($user, '0', '登陆成功','json');
    }
    
    
    
}
